<?php

namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use service\ToolsService;
use think\Db;
use think\exception\HttpResponseException;

/**
 * 商品管理
 */
class Goods extends BasicAdmin
{

    /**
     * 定义当前操作表名
     * @var string
     */
    public $goods = 'jixie_goods';
    public $goods_cate = 'jixie_goods_cate';

    /**
     * 普通商品
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $this->title = '商品管理';
        $get = $this->request->get();
        $db = Db::name($this->goods)
            ->alias('a')
            ->join($this->goods_cate . ' b', 'b.cate_id=a.cate_id', 'left')
            ->field('a.*,b.name as cate_name');


        if (isset($get['goods_name']) && $get['goods_name'] !== '') {
            $db->whereLike('goods_name', "%{$get['goods_name']}%");
        }
        foreach (['cate_id'] as $field) {
            (isset($get[$field]) && $get[$field] !== '') && $db->where('a.' . $field, $get[$field]);
        }
        if (isset($get['create_at']) && $get['create_at'] !== '') {
            list($start, $end) = explode(' - ', $get['create_at']);
            $db->whereBetween('a.create_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        }
        return parent::_list($db->order('goods_id desc'), 'goods_id');
    }

    /**
     * 商城数据处理
     * @param array $data
     */
    protected function _data_filter(&$data)
    {
        $result = $this->buildCateList($data);
        $this->assign([
            'cates' => ToolsService::arr2table($result['cate'], 'cate_id'),
        ]);
    }


    protected function buildCateList(&$data)
    {
        // 产品分类处理
        $cateField = 'cate_id,pid,name';
        $cateWhere = ['is_deleted' => '0'];
        $cateList = Db::name($this->goods_cate)->where($cateWhere)->order('sort asc,cate_id desc')->column($cateField);

        return ['list' => $data, 'cate' => $cateList];
    }

    /**
     * 添加商品
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function add()
    {
        if ($this->request->isGet()) {
            $this->title = '添加商品';
            $this->_form_assign();
            return $this->_form($this->goods, 'form');
        }
        try {
            $data = $this->_form_build_data();
            Db::transaction(function () use ($data) {
                Db::name($this->goods)->insertGetId($data['main']);
            });
        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('商品添加失败，请稍候再试！');
        }
        list($base, $spm, $url) = [url('@admin'), $this->request->get('spm'), url('goods/index')];
        $this->success('添加商品成功！', "{$base}#{$url}?spm={$spm}");
    }

    /**
     * 编辑商品
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        if (!$this->request->isPost()) {
            $goods_id = $this->request->get('id');
            $goods = Db::name($this->goods)->where(['goods_id' => $goods_id])->find();
            empty($goods) && $this->error('需要编辑的商品不存在！');
            $this->_form_assign();
            return $this->fetch('form', ['vo' => $goods, 'title' => '编辑商品']);
        }
        try {
            $data = $this->_form_build_data();
            $goods_id = $this->request->post('id');
            $goods = Db::name($this->goods)->where(['goods_id' => $goods_id])->find();
            empty($goods) && $this->error('商品编辑失败，请稍候再试！');
            foreach ($data['list'] as &$vo) {
                $vo['goods_id'] = $goods_id;
            }
            Db::transaction(function () use ($data, $goods_id, $goods) {
                // 更新商品主表
                $where = ['goods_id' => $goods_id];
                Db::name($this->goods)->where($where)->update(array_merge($goods, $data['main']));
            });
        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('商品编辑失败，请稍候再试！' . $e->getMessage());
        }
        list($base, $spm, $url) = [url('@admin'), $this->request->get('spm'), url('goods/index')];
        $this->success('商品编辑成功！', "{$base}#{$url}?spm={$spm}");
    }

    /**
     * 表单数据处理
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_assign()
    {
        list($where, $order) = [['is_deleted' => '0'], 'sort asc,cate_id desc'];
        $cates = (array)Db::name($this->goods_cate)->where($where)->order($order)->select();

        $data = Db::name($this->goods)->field('goods_id,goods_name')->select();
        $this->assign([
            'cates' => ToolsService::arr2table($cates, 'cate_id'),
            'all' => $data,
        ]);
    }

    /**
     * 读取POST表单数据
     * @return array
     */
    protected function _form_build_data()
    {
        list($main, $list, $post) = [[], [], $this->request->post()];
        empty($post['goods_pic']) && $this->error('商品图片不能为空，请上传后再提交数据！');
        // 商品主数据组装
        $main['cate_id'] = $this->request->post('cate_id', '0');
        $main['goods_pic'] = $this->request->post('goods_pic', '');
        $main['goods_name'] = $this->request->post('goods_name', '');
        $main['goods_price'] = $this->request->post('goods_price', '');
        $main['content'] = $this->request->post('content', '');
        $main['present'] = $this->request->post('present', ''); //赠送产品
        return ['main' => $main, 'list' => $list];
    }

    /**
     * 删除商品
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del()
    {
        if (DataService::update($this->goods)) {
            $this->success("商品删除成功！", '');
        }
        $this->error("商品删除失败，请稍候再试！");
    }

    /**
     * 商品禁用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        if (DataService::update($this->goods)) {
            $this->success("商品下架成功！", '');
        }
        $this->error("商品下架失败，请稍候再试！");
    }

    /**
     * 商品禁用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        if (DataService::update($this->goods)) {
            $this->success("商品上架成功！", '');
        }
        $this->error("商品上架失败，请稍候再试！");
    }

}
